package org.benxiong.iplay.ui.component;

import org.benxiong.iplay.R;
import org.benxiong.iplay.http.request.RequestFactory;
import org.benxiong.iplay.model.UserPhoto;
import org.benxiong.iplay.service.CacheService;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageButton;

import com.loopj.android.http.BinaryHttpResponseHandler;

public class UserPhotoThumbnail extends ImageButton {

	private UserPhoto	photo;
	private boolean		unlocked;
	private int			index;

	public UserPhotoThumbnail(Context context, UserPhoto photo, OnClickListener listener, boolean unlocked, int index) {
		super(context);
		this.photo = photo;
		this.unlocked = unlocked;
		this.index = index;
		this.setOnClickListener(listener);
		loadImage();
	}

	private void loadImage() {
		if (!this.unlocked) {
			// TODO: return a default lock icon, replace the listener with
			// showing 'locked photo'
			setImageResource(R.drawable.default_avator);
			return;
		}
		final UserPhotoThumbnail imageView = this;
		// TODO: show loading indicator

		Bitmap cached = CacheService.getBitmapFromCache(photo.getThumbnailUrl(), true);
		if (cached != null) {
			imageView.setImageBitmap(cached);
		} else {
			RequestFactory.getInstance().getPic(photo.getThumbnailUrl(), new BinaryHttpResponseHandler() {
				@Override
				public void onFailure(Throwable arg0, byte[] arg1) {
					// TODO Auto-generated method stub
					super.onFailure(arg0, arg1);
				}

				@Override
				public void onSuccess(byte[] data) {
					// TODO Auto-generated method stub
					super.onSuccess(data);
					if (data == null) {
						return;
					}
					Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
					imageView.setImageBitmap(bitmap);
					CacheService.addBitmapToCache(photo.getThumbnailUrl(), bitmap, true);
				}

				@Override
				public void onSuccess(int arg0, byte[] arg1) {
					// TODO Auto-generated method stub
					super.onSuccess(arg0, arg1);
				}

			});
		}
	}

	public UserPhoto getPhoto() {
		return photo;
	}

	public void setPhoto(UserPhoto photo) {
		this.photo = photo;
		this.loadImage();
	}

	public int getIndex() {
		return index;
	}

	public void setIndex(int index) {
		this.index = index;
	}

}
